package leetcode;

public class two2 {
    /**
     * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
     * 输出：7 -> 0 -> 8
     * 原因：342 + 465 = 807
     * */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        boolean size = false;
        String result = "";
        String s = String.valueOf(l1.val);
        String s1 = String.valueOf(l2.val);
        for(int i=0;i<s.length();i++){
            if(i<s1.length()){
                int num = Integer.parseInt(s.substring(i,i+1))+Integer.parseInt(s1.substring(i,i+1));
                if(num>=10){
                    size = true;
                    result += num%10;
                } else{
                    if(size){
                        size = false;
                        result += num+1;
                    }else {
                        result += num;
                    }
                }
            }else {
                result += s.substring(i,i+1);
            }
        }
        int parseInt = Integer.parseInt(result);
        System.out.println(parseInt);
        return new ListNode(parseInt);
    }

    public static ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while(l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;

            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);

            cur = cur.next;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
        if(carry == 1) {
            cur.next = new ListNode(carry);
        }
        System.out.println(pre.next.val);
        return pre.next;
    }

    // 还是不理解
    public ListNode addTwoNumbers3(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while(l1 != null || l2 != null){
            int x = l1 == null?0:l1.val;
            int y = l2 == null?0:l2.val;
            int sum = x + y + carry;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            carry = sum>9?1:0;
            if(l1!=null){
                l1 = l1.next;
            }else{
                l1 = null;
            }
            if(l2!=null){
                l2 = l2.next;
            }else{
                l2 = null;
            }
        }
        if(carry == 1) {
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        l1.next = new ListNode(7);
        l1.next.next = new ListNode(7);
        ListNode l2 = new ListNode(3);
        l2.next = new ListNode(1);
        l2.next.next = new ListNode(1);
        System.out.println(addTwoNumbers2(l1,l2));
    }
}
